package com.huifaapp.mall.fragment;


import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.AssessActivity;
import com.huifaapp.mall.activity.OrderdetailsActivity;
import com.huifaapp.mall.adapter.PendingCommAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.PendingCommBean;
import com.huifaapp.mall.bean.event.OrderStatusEventMessage;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 *待评论
 * A simple {@link Fragment} subclass.
 */
public class PendingCommFragment extends Fragment {


    private RecyclerView PendComm;
    private List<PendingCommBean.OrderListBean> list;
    private PendingCommAdapter pendingCommAdapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_pending_comm, container, false);
        initView(view);
        PendComm.setLayoutManager(new LinearLayoutManager(getActivity()));
        EventBus.getDefault().register(this);
        return view;
    }
    @Subscribe
    public void onEvent(OrderStatusEventMessage orderStatusEventMessage) {

        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notjudged")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(getActivity()))
//                "")
                .build().execute(new StringCallback() {

            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {

                Log.i("pecommHB",response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray orderList = jsonObject.getJSONArray("orderList");
                    Log.e("FH",orderList+"");
                    initData(response);
                } catch (JSONException e) {
                    Log.e("FH","HHH");
                }

            }
        });


        pendingCommAdapter.notifyDataSetChanged();
    }
    private boolean isGetData = false;
    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        //   进入当前Fragment
        if (enter && !isGetData) {
            isGetData = true;
            OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notjudged")
                    .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                    .addParams("appId", AUniqueIdentifier.getDeviceId(getActivity()))
//                "")
                    .build().execute(new StringCallback() {

                @Override
                public void onError(Request request, Exception e) {

                }

                @Override
                public void onResponse(String response) {

                    Log.i("pecommHB",response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray orderList = jsonObject.getJSONArray("orderList");
                        Log.e("FH",orderList+"");
                        initData(response);
                    } catch (JSONException e) {
                        Log.e("FH","HHH");
                    }

                }
            });
            //   这里可以做网络请求或者需要的数据刷新操作
        } else {
            isGetData = false;
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isGetData) {
            OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notjudged")
                    .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                    .addParams("appId", AUniqueIdentifier.getDeviceId(getActivity()))
//                "")
                    .build().execute(new StringCallback() {

                @Override
                public void onError(Request request, Exception e) {

                }

                @Override
                public void onResponse(String response) {

                    Log.i("pecommHB",response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray orderList = jsonObject.getJSONArray("orderList");
                        Log.e("FH",orderList+"");
                        initData(response);
                    } catch (JSONException e) {
                        Log.e("FH","HHH");
                    }

                }
            });
            //   这里可以做网络请求或者需要的数据刷新操作
            isGetData = true;
        }
    }
    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        isGetData = false;
        super.onDestroy();
    }


    private void initView(View view) {
        Log.e("评价信息",ApiManager.BASE_NIUPAI_URL+"orders/notjudged"+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&appId="+AUniqueIdentifier.getDeviceId(getActivity()));
        PendComm = (RecyclerView) view.findViewById(R.id.pendcomm_rv);
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notjudged")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(getActivity()))
//                "")
                .build().execute(new StringCallback() {

            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {

                Log.i("pecommHB",response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray orderList = jsonObject.getJSONArray("orderList");
                    Log.e("FH",orderList+"");
                    initData(response);
                } catch (JSONException e) {
                    Log.e("FH","HHH");
                }

            }
        });
    }

    private void initData(String response) {

        Gson gson = new Gson();
        PendingCommBean pendingCommBean = gson.fromJson(response, PendingCommBean.class);
        list = pendingCommBean.getOrderList();
        pendingCommAdapter = new PendingCommAdapter(getActivity(), list);
        PendComm.setAdapter(pendingCommAdapter);
        pendingCommAdapter.setOkItck(new PendingCommAdapter.OkItck() {
            @Override
            public void okck(View view, int position) {

            }

            @Override
            public void delete(View view, final int position) {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("是否需要删除？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                final String id = list.get(position).getOrderNo();
                                OkHttpUtils.post().url("http://develop.jhjvip.cn:8080/mall/mobile/orders/delorders")
                                        .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                        .addParams("appId", AUniqueIdentifier.getDeviceId(getActivity()))
                                        .addParams("orderNo",id)
                                        .build()
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onError(Request request, Exception e) {
                                                ToastUtils.showShort("删除失败");
                                            }

                                            @Override
                                            public void onResponse(String response) {
                                                Log.e("HB",response);
                                                try {
                                                    JSONObject jsonObject = new JSONObject(response);
                                                    String code =  jsonObject.getString("code");
                                                    if (code.equals("10000"))
                                                    {
                                                        list.remove(position);
                                                        pendingCommAdapter.notifyDataSetChanged();
                                                    }else {
                                                        ToastUtils.showShort("删除失败");
                                                    }

                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }


                                            }
                                        });

                            }
                        }).create();
                alertDialog.show();

            }

            @Override
            public void asaes(View view, int position) {
                Log.e("评论订单号",list.get(position).getOrderNo());
                Intent intent = new Intent(getActivity(), AssessActivity.class);
//                intent.putExtra("skuid",list.get(position)+"");
                intent.putExtra("oderId",list.get(position).getOrderNo());
                startActivity(intent);


            }

            @Override
            public void xiangqing(View view, int position) {
                Intent intent = new Intent(getActivity(), OrderdetailsActivity.class);
                intent.putExtra("orderNo",list.get(position).getOrderNo()+"");
                startActivity(intent);
            }
        });
    }


}
